package ee.ut.battleship;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class UpdateLobby
 */
@WebServlet("/UpdateLobby")
public class UpdateLobby extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public static List<Game> gamesList = new ArrayList<Game>();

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateLobby() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			response.setContentType("plain/text");
			Client client = LoginServlet.getClientByName(request.getParameter("clientName"));
			response.getWriter().write(client.getUpdateLobbyList().take());
			
		}catch (Exception e) {
			
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
			Gson gson = new Gson();
			PrintWriter out = response.getWriter();
			String json = gson.toJson(gamesList);
			out.write(json);
			
	}
	
	public static Game findGameByClientName(String client){
		for (Game game : gamesList){
			if (game.getPlayerOne().equals(client) || game.getPlayerTwo().equals(client)){
				return game;
			}
		}
		
		return null;
		
	}

}
